package cn.schoolwow.util.module.replace.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.replace.domain.ReplaceFileOption;

import java.io.*;
import java.nio.file.Files;
import java.util.Map;

public class ReplaceFileFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ReplaceFileOption replaceFileOption = (ReplaceFileOption) flowContext.checkData("replaceFileOption");

        if(!replaceFileOption.file.exists()){
            throw new IllegalArgumentException("原始不存在!路径:["+replaceFileOption.file.getAbsolutePath()+"]");
        }
        File renameFile = new File(replaceFileOption.file.getAbsolutePath() + ".tmp");

        try (BufferedReader reader = new BufferedReader(new FileReader(replaceFileOption.file));
             BufferedWriter writer = new BufferedWriter(new FileWriter(renameFile));
        ){
            String line;
            while ((line = reader.readLine()) != null) {
                String modifiedLine = line;
                //普通字符串替换
                for (Map.Entry<String, String> entry : replaceFileOption.replaceStringMap.entrySet()) {
                    modifiedLine = modifiedLine.replace(entry.getKey(), entry.getValue());
                }
                //正则替换
                for (Map.Entry<String, String> entry : replaceFileOption.regexReplaceStringMap.entrySet()) {
                    modifiedLine = modifiedLine.replaceAll(entry.getKey(), entry.getValue());
                }
                writer.write(modifiedLine);
                writer.newLine();
            }
        }
        Files.deleteIfExists(replaceFileOption.file.toPath());

        if(!renameFile.renameTo(replaceFileOption.file)){
            throw new IllegalArgumentException("重命名文件失败!重命名文件路径:["+renameFile.getAbsolutePath()+"]");
        }
    }

    @Override
    public String name() {
        return "替换文件内容";
    }
}
